<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>初学BlockingQueue | Unknown Blog</title><meta name="author" content="Ris Pika"><meta name="copyright" content="Ris Pika"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="1.什么是队列-&gt;特性FIFO(先见先出) 先进入的对象,先出来,与栈(先进后出)相反 2.阻塞队列和队列有什么区别?-&gt;主要是强调在(阻塞)上!即在(取)的时候,如果队列为空,则进行等待 在(存)的时候,如果队列已满,则进行等待 -&gt;Queue同样继承Collection,与List,Set同级而BlockingQueue继承与Queue  同样BlockingQueue拥有这">
<meta property="og:type" content="article">
<meta property="og:title" content="初学BlockingQueue">
<meta property="og:url" content="https://unkonwn.online/2023/02/27/blocking-queue/index.html">
<meta property="og:site_name" content="Unknown Blog">
<meta property="og:description" content="1.什么是队列-&gt;特性FIFO(先见先出) 先进入的对象,先出来,与栈(先进后出)相反 2.阻塞队列和队列有什么区别?-&gt;主要是强调在(阻塞)上!即在(取)的时候,如果队列为空,则进行等待 在(存)的时候,如果队列已满,则进行等待 -&gt;Queue同样继承Collection,与List,Set同级而BlockingQueue继承与Queue  同样BlockingQueue拥有这">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="http://pic.unkonwn.online/wallhaven-we52yp.jpg?imageView/1/w/240/h/240">
<meta property="article:published_time" content="2023-02-27T07:50:33.000Z">
<meta property="article:modified_time" content="2023-02-28T10:06:30.873Z">
<meta property="article:author" content="Ris Pika">
<meta property="article:tag" content="java">
<meta property="article:tag" content="BlockingQueue">
<meta property="article:tag" content="多线程">
<meta property="article:tag" content="并发">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://pic.unkonwn.online/wallhaven-we52yp.jpg?imageView/1/w/240/h/240"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://unkonwn.online/2023/02/27/blocking-queue/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/font-awesome/6.0.0/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/node-snackbar/0.1.16/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","languages":{"hits_empty":"We didn't find any results for the search: ${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"Traditional Chinese Activated Manually","cht_to_chs":"Simplified Chinese Activated Manually","day_to_night":"Dark Mode Activated Manually","night_to_day":"Light Mode Activated Manually","bgLight":"#49b1f5","bgDark":"#121212","position":"top-right"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '初学BlockingQueue',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-02-28 18:06:30'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.2"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">Loading...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })

if (false) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="http://pic.unkonwn.online//20140802211120_t34dW.jpeg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">6</div></a><a href="/tags/"><div class="headline">Tags</div><div class="length-num">13</div></a><a href="/categories/"><div class="headline">Categories</div><div class="length-num">0</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/upadte/"><i class="fa-fw fa fa-bell"></i><span> 日志</span></a></div><div class="menus_item"><a class="site-page" href="/myself/"><i class="fa-fw fa fa-id-card"></i><span> Myself</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-list"></i><span> 菜单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/%E5%85%B3%E4%BA%8E"><i class="fa-fw /about/"></i><span> 0</span></a></li><li><a class="site-page child" href="/butterfly%E4%B8%BB%E9%A2%98"><i class="fa-fw https://github.com/jerryc127/hexo-theme-butterfly/"></i><span> 1</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('http://pic.unkonwn.online/wallhaven-we52yp.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="Unknown Blog"><span class="site-name">Unknown Blog</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> Search</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/upadte/"><i class="fa-fw fa fa-bell"></i><span> 日志</span></a></div><div class="menus_item"><a class="site-page" href="/myself/"><i class="fa-fw fa fa-id-card"></i><span> Myself</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-list"></i><span> 菜单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/%E5%85%B3%E4%BA%8E"><i class="fa-fw /about/"></i><span> 0</span></a></li><li><a class="site-page child" href="/butterfly%E4%B8%BB%E9%A2%98"><i class="fa-fw https://github.com/jerryc127/hexo-theme-butterfly/"></i><span> 1</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">初学BlockingQueue</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2023-02-27T07:50:33.000Z" title="Created 2023-02-27 15:50:33">2023-02-27</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2023-02-28T10:06:30.873Z" title="Updated 2023-02-28 18:06:30">2023-02-28</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="初学BlockingQueue"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="1-什么是队列"><a href="#1-什么是队列" class="headerlink" title="1.什么是队列"></a>1.什么是队列</h2><h3 id="gt-特性"><a href="#gt-特性" class="headerlink" title="-&gt;特性"></a>-&gt;特性</h3><p><strong>FIFO(先见先出)</strong></p>
<p><strong>先进入的对象,先出来,与栈(先进后出)相反</strong></p>
<h2 id="2-阻塞队列和队列有什么区别"><a href="#2-阻塞队列和队列有什么区别" class="headerlink" title="2.阻塞队列和队列有什么区别?"></a>2.阻塞队列和队列有什么区别?</h2><h3 id="gt-主要是强调在-阻塞-上"><a href="#gt-主要是强调在-阻塞-上" class="headerlink" title="-&gt;主要是强调在(阻塞)上!"></a>-&gt;主要是强调在(阻塞)上!</h3><p><strong>即在(取)的时候,如果队列为空,则进行等待</strong></p>
<p><strong>在(存)的时候,如果队列已满,则进行等待</strong></p>
<h3 id="gt-Queue同样继承Collection-与List-Set同级"><a href="#gt-Queue同样继承Collection-与List-Set同级" class="headerlink" title="-&gt;Queue同样继承Collection,与List,Set同级"></a>-&gt;Queue同样继承Collection,与List,Set同级</h3><p><strong>而BlockingQueue继承与Queue</strong></p>
<p><img src= "" data-lazy-src="http://pic.unkonwn.online//20230227174018.png" alt="image-20230227112737205"></p>
<p><strong>同样BlockingQueue拥有这Linked和Array的子类</strong></p>
<h3 id="gt-而在什么情况下我们会使用阻塞队列"><a href="#gt-而在什么情况下我们会使用阻塞队列" class="headerlink" title="-&gt;而在什么情况下我们会使用阻塞队列"></a>-&gt;而在什么情况下我们会使用阻塞队列</h3><p><strong>-&gt;多线程并发,使用线程池的情况下</strong></p>
<p><strong>-&gt;总体继承关系</strong></p>
<p><img src= "" data-lazy-src="http://pic.unkonwn.online//20230227174050.png"></p>
<h3 id="四组API的异或"><a href="#四组API的异或" class="headerlink" title="四组API的异或"></a>四组API的异或</h3><table>
<thead>
<tr>
<th>方式</th>
<th>抛出异常</th>
<th>不抛出异常</th>
<th>一直等待(阻塞)</th>
<th>等待超时(超时即退出)</th>
</tr>
</thead>
<tbody><tr>
<td>添加</td>
<td>add(o)</td>
<td>offer(o)</td>
<td>put(o)</td>
<td>offer(o,time,TimeUnit)</td>
</tr>
<tr>
<td>删除</td>
<td>remove()</td>
<td>poll()</td>
<td>take()</td>
<td>poll(o,time,TimeUnit)</td>
</tr>
<tr>
<td>检查队首元素</td>
<td>element()</td>
<td>peek()</td>
<td>-</td>
<td>-</td>
</tr>
</tbody></table>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 抛出异常</span></span><br><span class="line"><span class="comment">   * ArrayBlockingQueue</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">arrayBlockingQueueDemo</span><span class="params">()</span> &#123;</span><br><span class="line">      ArrayBlockingQueue&lt;Object&gt; arrayBlockingQueue = <span class="keyword">new</span> <span class="title class_">ArrayBlockingQueue</span>&lt;&gt;(<span class="number">3</span>);<span class="comment">//队列大小</span></span><br><span class="line">      System.out.println(arrayBlockingQueue.add(<span class="string">&quot;a&quot;</span>));</span><br><span class="line">      System.out.println(arrayBlockingQueue.add(<span class="string">&quot;b&quot;</span>));</span><br><span class="line">      System.out.println(arrayBlockingQueue.add(<span class="string">&quot;c&quot;</span>)); <span class="comment">// true , true , true</span></span><br><span class="line"><span class="comment">//System.out.println(arrayBlockingQueue.add(&quot;报错&quot;));</span></span><br><span class="line">      <span class="comment">//java.lang.IllegalStateException: Queue full</span></span><br><span class="line">      System.out.println(arrayBlockingQueue.remove());</span><br><span class="line">      System.out.println(arrayBlockingQueue.remove());</span><br><span class="line">      System.out.println(arrayBlockingQueue.remove()); <span class="comment">// a , b , c</span></span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 又返回值,不抛出异常</span></span><br><span class="line"><span class="comment"> * ArrayBlockingQueue</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">arrayBlockingQueueDemo2</span><span class="params">()</span> &#123;</span><br><span class="line">    ArrayBlockingQueue&lt;Object&gt; arrayBlockingQueue = <span class="keyword">new</span> <span class="title class_">ArrayBlockingQueue</span>&lt;&gt;(<span class="number">3</span>);<span class="comment">//队列大小</span></span><br><span class="line">    System.out.println(arrayBlockingQueue.offer(<span class="string">&quot;a&quot;</span>));</span><br><span class="line">    System.out.println(arrayBlockingQueue.offer(<span class="string">&quot;b&quot;</span>));</span><br><span class="line">    System.out.println(arrayBlockingQueue.offer(<span class="string">&quot;c&quot;</span>));</span><br><span class="line">    System.out.println(arrayBlockingQueue.offer(<span class="string">&quot;报错&quot;</span>));<span class="comment">// true , true , true, flase</span></span><br><span class="line">    System.out.println(arrayBlockingQueue.poll());</span><br><span class="line">    System.out.println(arrayBlockingQueue.poll());</span><br><span class="line">    System.out.println(arrayBlockingQueue.poll()); <span class="comment">// a , b , c</span></span><br><span class="line">    System.out.println(arrayBlockingQueue.poll()); <span class="comment">// a , b , c, null</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>-&gt;其他的自己敲把~&lt;-</strong></p>
<h2 id="3-SynchronousQueue-与-BlockingQueue"><a href="#3-SynchronousQueue-与-BlockingQueue" class="headerlink" title="3.SynchronousQueue 与 BlockingQueue"></a>3.SynchronousQueue 与 BlockingQueue</h2><h3 id="gt-区别"><a href="#gt-区别" class="headerlink" title="-&gt;区别"></a>-&gt;区别</h3><p><strong>SynchronousQueue 就类似于只有一个大小的队列,只有当队列内的对象被取出后,才可以继续存储</strong></p>
<p><strong>而 BlockingQueue 可以自定义队列的大小,调用四组 api (见上方)进项操作</strong></p>
<h3 id="gt-代码"><a href="#gt-代码" class="headerlink" title="-&gt;代码"></a>-&gt;代码</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 同步队列</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">test2</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="comment">// 创建同步队列对象</span></span><br><span class="line">    BlockingQueue&lt;Object&gt; synchronousQueue = <span class="keyword">new</span> <span class="title class_">SynchronousQueue</span>&lt;&gt;();</span><br><span class="line">    <span class="comment">// 放入</span></span><br><span class="line">    <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            System.out.println(Thread.currentThread().getName()+<span class="string">&quot;放入a&quot;</span>);</span><br><span class="line">            synchronousQueue.put(<span class="string">&quot;a&quot;</span>);</span><br><span class="line">            System.out.println(Thread.currentThread().getName()+<span class="string">&quot;放入b&quot;</span>);</span><br><span class="line">            synchronousQueue.put(<span class="string">&quot;b&quot;</span>);</span><br><span class="line">            System.out.println(Thread.currentThread().getName()+<span class="string">&quot;放入c&quot;</span>);</span><br><span class="line">            synchronousQueue.put(<span class="string">&quot;c&quot;</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;, <span class="string">&quot;t1&quot;</span>).start();</span><br><span class="line">    <span class="comment">// 拿出</span></span><br><span class="line">    <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">1</span>);</span><br><span class="line">            System.out.println(Thread.currentThread().getName()+<span class="string">&quot;删除a&quot;</span>);</span><br><span class="line">            synchronousQueue.take();</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">1</span>);</span><br><span class="line">            System.out.println(Thread.currentThread().getName()+<span class="string">&quot;删除b&quot;</span>);</span><br><span class="line">            synchronousQueue.take();</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">1</span>);</span><br><span class="line">            System.out.println(Thread.currentThread().getName()+<span class="string">&quot;删除c&quot;</span>);</span><br><span class="line">            synchronousQueue.take();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;, <span class="string">&quot;t2&quot;</span>).start();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="https://unkonwn.online">Ris Pika</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="https://unkonwn.online/2023/02/27/blocking-queue/">https://unkonwn.online/2023/02/27/blocking-queue/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/java/">java</a><a class="post-meta__tags" href="/tags/BlockingQueue/">BlockingQueue</a><a class="post-meta__tags" href="/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/">多线程</a><a class="post-meta__tags" href="/tags/%E5%B9%B6%E5%8F%91/">并发</a></div><div class="post_share"><div class="social-share" data-image="http://pic.unkonwn.online/wallhaven-we52yp.jpg?imageView/1/w/240/h/240" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://lib.baomitu.com/social-share.js/1.0.16/css/share.min.css" media="print" onload="this.media='all'"><script src="https://lib.baomitu.com/social-share.js/1.0.16/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/02/28/JAVA%E7%BA%BF%E7%A8%8B%E6%B1%A0%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/" title="JAVA线程池学习日记1"><img class="cover" src= "" data-lazy-src="https://pic.unkonwn.online//wallhaven-x6ewo3.jpg?imageView/1/w/500/h/500" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">Previous Post</div><div class="prev_info">JAVA线程池学习日记1</div></div></a></div><div class="next-post pull-right"><a href="/2023/02/26/jwt/" title="五分钟JWT入门"><img class="cover" src= "" data-lazy-src="http://pic.unkonwn.online/wallhaven-qzr7pr.jpg?imageView/1/w/240/h/240" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">Next Post</div><div class="next_info">五分钟JWT入门</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>Related Articles</span></div><div class="relatedPosts-list"><div><a href="/2023/02/26/jwt/" title="五分钟JWT入门"><img class="cover" src= "" data-lazy-src="http://pic.unkonwn.online/wallhaven-qzr7pr.jpg?imageView/1/w/240/h/240" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-26</div><div class="title">五分钟JWT入门</div></div></a></div><div><a href="/2023/02/28/JAVA%E7%BA%BF%E7%A8%8B%E6%B1%A0%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/" title="JAVA线程池学习日记1"><img class="cover" src= "" data-lazy-src="https://pic.unkonwn.online//wallhaven-x6ewo3.jpg?imageView/1/w/500/h/500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-28</div><div class="title">JAVA线程池学习日记1</div></div></a></div><div><a href="/2023/03/01/JUC%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/" title="JUC学习日记1"><img class="cover" src= "" data-lazy-src="https://pic.unkonwn.online//wallhaven-6dl2yw.jpg?imageView/1/w/500/h/500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-01</div><div class="title">JUC学习日记1</div></div></a></div><div><a href="/2023/03/01/JAVA-%E4%BB%8E0%E5%88%B0helloworld/" title="JAVA 从0到helloworld"><img class="cover" src= "" data-lazy-src="https://pic.unkonwn.online//wallhaven-gpw787.jpg?imageView/1/w/500/h/500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-01</div><div class="title">JAVA 从0到helloworld</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="http://pic.unkonwn.online//20140802211120_t34dW.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Ris Pika</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">6</div></a><a href="/tags/"><div class="headline">Tags</div><div class="length-num">13</div></a><a href="/categories/"><div class="headline">Categories</div><div class="length-num">0</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/rispika/"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>Announcement</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E4%BB%80%E4%B9%88%E6%98%AF%E9%98%9F%E5%88%97"><span class="toc-number">1.</span> <span class="toc-text">1.什么是队列</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#gt-%E7%89%B9%E6%80%A7"><span class="toc-number">1.1.</span> <span class="toc-text">-&gt;特性</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E9%98%BB%E5%A1%9E%E9%98%9F%E5%88%97%E5%92%8C%E9%98%9F%E5%88%97%E6%9C%89%E4%BB%80%E4%B9%88%E5%8C%BA%E5%88%AB"><span class="toc-number">2.</span> <span class="toc-text">2.阻塞队列和队列有什么区别?</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#gt-%E4%B8%BB%E8%A6%81%E6%98%AF%E5%BC%BA%E8%B0%83%E5%9C%A8-%E9%98%BB%E5%A1%9E-%E4%B8%8A"><span class="toc-number">2.1.</span> <span class="toc-text">-&gt;主要是强调在(阻塞)上!</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#gt-Queue%E5%90%8C%E6%A0%B7%E7%BB%A7%E6%89%BFCollection-%E4%B8%8EList-Set%E5%90%8C%E7%BA%A7"><span class="toc-number">2.2.</span> <span class="toc-text">-&gt;Queue同样继承Collection,与List,Set同级</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#gt-%E8%80%8C%E5%9C%A8%E4%BB%80%E4%B9%88%E6%83%85%E5%86%B5%E4%B8%8B%E6%88%91%E4%BB%AC%E4%BC%9A%E4%BD%BF%E7%94%A8%E9%98%BB%E5%A1%9E%E9%98%9F%E5%88%97"><span class="toc-number">2.3.</span> <span class="toc-text">-&gt;而在什么情况下我们会使用阻塞队列</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9B%9B%E7%BB%84API%E7%9A%84%E5%BC%82%E6%88%96"><span class="toc-number">2.4.</span> <span class="toc-text">四组API的异或</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-SynchronousQueue-%E4%B8%8E-BlockingQueue"><span class="toc-number">3.</span> <span class="toc-text">3.SynchronousQueue 与 BlockingQueue</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#gt-%E5%8C%BA%E5%88%AB"><span class="toc-number">3.1.</span> <span class="toc-text">-&gt;区别</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#gt-%E4%BB%A3%E7%A0%81"><span class="toc-number">3.2.</span> <span class="toc-text">-&gt;代码</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>Recent Post</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/03/01/JAVA-%E4%BB%8E0%E5%88%B0helloworld/" title="JAVA 从0到helloworld"><img src= "" data-lazy-src="https://pic.unkonwn.online//wallhaven-gpw787.jpg?imageView/1/w/500/h/500" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JAVA 从0到helloworld"/></a><div class="content"><a class="title" href="/2023/03/01/JAVA-%E4%BB%8E0%E5%88%B0helloworld/" title="JAVA 从0到helloworld">JAVA 从0到helloworld</a><time datetime="2023-03-01T14:32:08.000Z" title="Created 2023-03-01 22:32:08">2023-03-01</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/03/01/JUC%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/" title="JUC学习日记1"><img src= "" data-lazy-src="https://pic.unkonwn.online//wallhaven-6dl2yw.jpg?imageView/1/w/500/h/500" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JUC学习日记1"/></a><div class="content"><a class="title" href="/2023/03/01/JUC%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/" title="JUC学习日记1">JUC学习日记1</a><time datetime="2023-03-01T12:52:40.000Z" title="Created 2023-03-01 20:52:40">2023-03-01</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/02/28/JAVA%E7%BA%BF%E7%A8%8B%E6%B1%A0%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/" title="JAVA线程池学习日记1"><img src= "" data-lazy-src="https://pic.unkonwn.online//wallhaven-x6ewo3.jpg?imageView/1/w/500/h/500" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JAVA线程池学习日记1"/></a><div class="content"><a class="title" href="/2023/02/28/JAVA%E7%BA%BF%E7%A8%8B%E6%B1%A0%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/" title="JAVA线程池学习日记1">JAVA线程池学习日记1</a><time datetime="2023-02-28T10:02:52.000Z" title="Created 2023-02-28 18:02:52">2023-02-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/02/27/blocking-queue/" title="初学BlockingQueue"><img src= "" data-lazy-src="http://pic.unkonwn.online/wallhaven-we52yp.jpg?imageView/1/w/240/h/240" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="初学BlockingQueue"/></a><div class="content"><a class="title" href="/2023/02/27/blocking-queue/" title="初学BlockingQueue">初学BlockingQueue</a><time datetime="2023-02-27T07:50:33.000Z" title="Created 2023-02-27 15:50:33">2023-02-27</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/02/26/jwt/" title="五分钟JWT入门"><img src= "" data-lazy-src="http://pic.unkonwn.online/wallhaven-qzr7pr.jpg?imageView/1/w/240/h/240" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="五分钟JWT入门"/></a><div class="content"><a class="title" href="/2023/02/26/jwt/" title="五分钟JWT入门">五分钟JWT入门</a><time datetime="2023-02-26T13:39:36.000Z" title="Created 2023-02-26 21:39:36">2023-02-26</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By Ris Pika</div><div class="framework-info"><span>Framework </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>Theme </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">unknown!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="Back To Top"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/vanilla-lazyload/17.3.1/lazyload.iife.min.js"></script><script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/node-snackbar/0.1.16/snackbar.min.js"></script><div class="js-pjax"></div><script defer src="/live2d-widget/autoload.js"></script><canvas class="fireworks" mobile="true"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/fireworks.min.js"></script><script defer="defer" id="fluttering_ribbon" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-nest.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">Search</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  Loading the Database</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="Search for Posts" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></body></html>